package chpt09.testsync;

public class SynchronizedStaticThreadTest {
	public static void main(String[] args) throws InterruptedException {
		int n = 10000; // 执行次数
		Thread t1 = new Thread(new Adder(n));
		Thread t2 = new Thread(new Adder(n));
		Thread t3 = new Thread(new Adder(n));
		Thread t4 = new Thread(new Subtracter(n));
		Thread t5 = new Thread(new Subtracter(n));
		Thread t6 = new Thread(new Subtracter(n));
		t1.start();	t2.start();	t3.start();	t4.start();	t5.start();	t6.start();
		t1.join();	t2.join();	t3.join();	t4.join();	t5.join();	t6.join();
		System.out.println(SyncStaticCounter.getValue());
		System.out.println("main end");
	}
}

class SyncStaticCounter {
	private static int value = 0;
	// 同步代码块
	public static void inc() { 
		synchronized (SyncStaticCounter.class) {
			value++;
		}
	}
	// 同步方法
	public static synchronized void dec() {
		value--;
	}
	// 只是读取操作，一般无需进行同步
	public static int getValue() {
		return value;
	}
}

class Adder implements Runnable {
	private int n; // 执行次数

	public Adder(int n) {
		this.n = n;
	}

	@Override
	public void run() {
		for (int i = 0; i < n; i++)
			SyncStaticCounter.inc();
		String name = Thread.currentThread().getName();
		System.out.println(name + " end");
	}
}

class Subtracter implements Runnable {
	private int n;

	public Subtracter(int n) {
		this.n = n;
	}

	@Override
	public void run() {
		for (int i = 0; i < n; i++)
			SyncStaticCounter.dec();
		String name = Thread.currentThread().getName();
		System.out.println(name + " end");
	}
}
